﻿package net.wangit.view.unit.sum;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;


public class SumRow implements Comparable {

	private static final String SUM_CSS = "SUM";
	private int rowIndex;
	private Map values;

	public SumRow(int rowIndex) {
		values = new HashMap();
		this.rowIndex = rowIndex;
	}

	public void setText(String name, String text) {
		values.put(name, text);
	}

	public void setTexts(UnitComponent uc, int rowIndex, int maxRowIndex,
			Element select, Element index) {
		uc.setRowCss(rowIndex, "SUM");
		for (int i = 0; i < uc.size(); i++) {
			ElementComponent ec = uc.getElementComponent(i);
			ec.moveExtendedAttribute(rowIndex, maxRowIndex);
			ec.setHtml(rowIndex, "");
		}

		if (select != null) {
			select.moveExtendedAttribute(rowIndex, maxRowIndex);
			select.setHtml(rowIndex, "");
		}
		if (index != null) {
			index.moveExtendedAttribute(rowIndex, maxRowIndex);
			index.setHtml(rowIndex, "");
		}
		MapList data = uc.getData();
		String key;
		String value;
		for (Iterator keys = values.keySet().iterator(); keys.hasNext(); data
				.put(rowIndex, key, value)) {
			key = (String) keys.next();
			Element element = uc.getElement(key);
			if (element == null)
				throw new SumConfigurationException((new StringBuilder(
						"Element \"")).append(key).append("\" not found:")
						.toString(), uc.getDomain(), uc.getId());
			value = (String) values.get(key);
			element.setHtml(rowIndex, value);
		}

	}

	public boolean isFilled(String name) {
		return values.containsKey(name);
	}

	public int getRowIndex() {
		return rowIndex;
	}

	public void setRealRowIndex(int offset) {
		rowIndex += offset;
	}

	public void setRowIndex(int offset, int maxRowIndex) {
		if (rowIndex < 0)
			rowIndex = maxRowIndex;
		else
			rowIndex -= offset;
	}

	public int compareTo(Object o) {
		return rowIndex - ((SumRow) o).getRowIndex();
	}
}
